package com.example.commons;

import com.example.commons.response.ErrorResource;
import jakarta.validation.ConstraintViolationException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.security.InvalidParameterException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(InvalidParameterException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResponseEntity<ErrorResource> handleInvalidParameterException(InvalidParameterException e) {
        return ResponseEntity.badRequest().body(ErrorResource.builder()
                .message(e.getMessage())
                .build());
    }

    @ExceptionHandler(IllegalArgumentException.class)
    public ResponseEntity<ErrorResource> handleIllegalArgumentException(
            IllegalArgumentException exception
    ) {
        return ResponseEntity.badRequest()
                .body(
                        ErrorResource.builder()
                                .message(exception.getMessage())
                                .build()
                );
    }




    @ExceptionHandler(NotFoundException.class)
    public ResponseEntity<ErrorResource> handleNotFoundException(
            NotFoundException exception
    ) {
        return ResponseEntity.status(HttpStatus.NOT_FOUND.value())
                .body(
                        ErrorResource.builder()
                                .message(exception.getMessage())
                                .build()
                );
    }


    @ExceptionHandler({ConstraintViolationException.class})
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    protected ResponseEntity<ErrorResource<?>> handleBindException(ConstraintViolationException ex) {
        List<Map<String, String>> errors = new ArrayList<>();
        ex.getConstraintViolations().forEach(violation -> {
            Map<String, String> error = new HashMap<>();
            error.put("field", violation.getPropertyPath().toString());
            error.put("message", violation.getMessage());
            errors.add(error);
        });
        return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                .body(ErrorResource.builder()
                        .message("Parameter error")
                        .data(errors)
                        .build());
    }
}
